/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

import fs from 'fs';
import path from 'path';

import { HvigorLogger } from '@ohos/hvigor';
import { Component } from '@ohos/sdkmanager-common';

import { getJson5Obj } from '../../utils/json-util.js';
import { SdkComponent } from '../superior/sdk-component.js';

/**
 * sdk previewer实例
 */
export class SdkPreviewerComponent extends SdkComponent {
  private readonly logger: HvigorLogger = HvigorLogger.getLogger(SdkPreviewerComponent.name);
  public static readonly COMMON = 'common';
  public static readonly BIN = 'bin';
  public static readonly RESOURCES_MODULE = 'resources/module.json';
  public readonly sdkDefinePermissions: Map<string, string[]> = new Map();
  public allowSdkPermission = false;

  constructor(component: Component) {
    super(component);
    this.setPermissionData();
  }

  public getCommonBin() {
    return path.resolve(this.getBaseDir(), SdkPreviewerComponent.COMMON, SdkPreviewerComponent.BIN);
  }

  private setPermissionData(): void {
    this.logger.debug('Start recording SDK configuration permission data.');
    const jsonPath = path.resolve(this.getBaseDir(), SdkPreviewerComponent.COMMON, SdkPreviewerComponent.RESOURCES_MODULE);
    if (!fs.existsSync(jsonPath)) {
      this.logger.debug(`The file does not exist. At ${jsonPath}`);
      return;
    }
    const permissions = getJson5Obj(jsonPath)?.module?.definePermissions;
    if (!permissions) {
      this.logger.warn(`Failed to obtain the valid permission list. Download the SDK again.\nat ${jsonPath} `);
      return;
    }
    permissions.forEach((item: { grantMode: string; name: string }) => {
      const grantMode = item.grantMode;
      const arr = this.sdkDefinePermissions.get(grantMode) || [];
      this.sdkDefinePermissions.set(grantMode, [...arr, item.name]);
    });
    this.allowSdkPermission = permissions.length > 0;
  }

  /**
   * 获取sdk配置权限名称集合
   *
   * @returns string[]
   */
  public getSdkPermissionNames(): string[] {
    return Array.from(this.sdkDefinePermissions.values()).reduce((permissions: string[], currentValue: string[]) => [...permissions, ...currentValue], []);
  }

  /**
   * 获取sdk配置用户权限名称集合
   *
   * @returns string[]
   */
  public getSdkDefineUserGrant(): string[] {
    return this.sdkDefinePermissions.get('user_grant') || [];
  }
}
